package com.zty.controller;

import com.alibaba.fastjson.JSONObject;
import com.zty.annotations.TokenVerify;
import com.zty.annotations.UserId;
import com.zty.pojo.Msg;
import com.zty.service.ShareService;
import com.zty.service.oss.OSSClient;
import com.zty.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.util.Date;

/**
 * @author admin
 */
@RestController
@RequestMapping("/api/share")
public class ShareController {
    @Autowired
    private ShareService shareService;

    @PostMapping("/addShare")
    public String addShare(@RequestBody JSONObject jsonObject, HttpServletRequest req, @UserId String userId) {
        String username = JwtUtil.getPayload(req.getHeader("token")).get("username").toString();
        String filePath = userId + jsonObject.get("filePath").toString();
        boolean isEncrypt = jsonObject.get("pwd").toString().equals("0");
        return shareService.addShare(username, new Date(), filePath, isEncrypt);

    }

    @PostMapping("/getShare")
    public String getShare(@RequestBody JSONObject jsonObject, HttpServletResponse res) throws IOException, ParseException {
        String number = jsonObject.get("number").toString();
        String pwd = jsonObject.get("pwd").toString();
        String path = shareService.getShare(number, pwd);
        if ("0".equals(path)) {
            return new Msg(1,"秘钥或提取码错误!",null).toJson();
        }

        String fileJson = new OSSClient().downloadFile(null, path);
        return new Msg(0,fileJson,null).toJson();
    }

    @GetMapping("/getShareList")
    public String getShareList(){
       return shareService.getShareList();
    }

    @GetMapping("/getShareMeList")
    @TokenVerify
    public String getShareMeList(HttpServletRequest req){
        String name = JwtUtil.getPayload(req.getHeader("token")).get("username").toString();
        return shareService.getShareMeList(name);
    }









}
